package com.example;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * context 作用:
 * 1. 共享数据
 * 2. 获取web.xml中的初始化参数
 */

@WebServlet("/getcontext")
public class GetContext extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ServletContext context = this.getServletContext();
        try {
            // 功能1. 获取由setAttribute()写入的变量的值
            resp.getWriter().write("<p>通过context获取setAttribute()写入的对象: </p>" + context.getAttribute("data"));
            // 功能2. 获取web.xml文件中存放的数据
            String initparam = context.getInitParameter("initparam");
            resp.getWriter().write("<p>通过context获取web.xml中写入的参数: </p>" + initparam);

            
            // 功能3. 请求转发
            // context.getRequestDispatcher("/home").forward(req, resp);

            // 功能4. 读取资源
            InputStream inStream = context.getClassLoader().getResourceAsStream("user.properties");
            Properties properties = new Properties();
            properties.load(inStream);
            String user = properties.getProperty("username");
            resp.getWriter().write("<p>通过context获取properties文件中写入的参数: </p>" + user);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
